import React, { useState, useRef, useEffect } from 'react';
import { Input, Space, Button, Modal, Table, Form, Typography, Popconfirm, InputNumber } from 'antd';
import { ClassifyStyle } from './style'
import { CheckCircleOutlined } from '@ant-design/icons';
import { useSelector,useDispatch } from "react-redux"
//从数据模型model中引入方法
import { goodsattr } from "../../model/goodsModel"

import { setStorage, getStorage } from '@/utils/LocalStorage'

const { Search } = Input;
const onSearch = value => console.log(value);


const Index = () => {
    // 表格
    const originData = getStorage("goodsAttribute") ? JSON.parse(getStorage("goodsAttribute")) : [];

    const dispatch = useDispatch()
    // 从redux中取数据
    // const data1 = useSelector(state=>state.getIn(["goods"])).toJS()

    const [visible, setVisible] = useState(false);
    //goodsattr的状态
    const [goodsAttr, setGoodattr] = useState([]);
    async function getGoodattr() {
        let data = await goodsattr()
        data = data.data.data
        let list = [...data , ...originData]
        setGoodattr(list)
        setData(list)
        dispatch({
            type:"goodssort",
            data:list
        })
        
    }

    useEffect(() => {
        getGoodattr()
        setData(originData)
        // console.log(data1.goodsSort)
    }, []);
    // 添加属性组和属性值
    const a1 = useRef()
    const a2 = useRef()

    

    const EditableCell = ({
        editing,
        dataIndex,
        title,
        inputType,
        record,
        index,
        children,
        ...restProps
    }) => {
        const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item
                        name={dataIndex}
                        style={{
                            margin: 0,
                        }}
                        rules={[
                            {
                                required: true,
                                message: `请输入${title}!`,
                            },
                        ]}
                    >
                        {inputNode}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };

    // 表格
    const [form] = Form.useForm();
    const [data, setData] = useState([]);

    const [editingKey, setEditingKey] = useState('');

    const isEditing = (record) => record.key === editingKey;
    const edit = (record) => {
        form.setFieldsValue({
            name: '',
            age: '',
            ...record,
        });
        setEditingKey(record.key);
    };

    const cancel = () => {
        setEditingKey('');
    };

    const save = async (key) => {
        try {
            const row = await form.validateFields();
            const newData = [...data];
            const index = newData.findIndex((item) => key === item.key);

            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, { ...item, ...row });
                setData(newData);
                setEditingKey('');
            } else {
                newData.push(row);
                setData(newData);
                setEditingKey('');
            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    };

    const columns = [
        {
            title: '属性组名称',
            dataIndex: 'name',
            width: '25%',
            editable: true,
        },
        {
            title: '包含属性',
            dataIndex: 'age',
            width: '40%',
            editable: true,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
                        <a
                            href="javascript:void(0);"
                            onClick={() => save(record.key)}
                            style={{
                                marginRight: 8,
                            }}
                        >
                            Save
                        </a>
                        <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
                            <a>Cancel</a>
                        </Popconfirm>
                    </span>
                ) : (
                    <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
                        修改
                    </Typography.Link>
                );
            },
        },
    ];
    const mergedColumns = columns.map((col) => {
        if (!col.editable) {
            return col;
        }

        return {
            ...col,
            onCell: (record) => ({
                record,
                inputType: col.dataIndex === 'age' ? 'number' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });


    return (
        <>
            <ClassifyStyle>
                <div className="goodsTop">
                    <span>商品管理</span>
                /
                    <span>编辑商品分类</span>
                </div>
                <hr />
                <div className="searchAdd">
                    <Space direction="vertical" className="search">
                        <Search
                            placeholder="请输入属性组名称"
                            allowClear
                            enterButton="搜索"
                            size="middle"
                            onSearch={onSearch}
                        />
                    </Space>
                    <Button onClick={() => setVisible(true)} type="primary" icon={<CheckCircleOutlined />}>
                        添加
                    </Button>
                    <Modal
                        title="添加属性组"
                        centered
                        visible={visible}
                        onOk={() => {
                            setVisible(false)
                            originData.push({
                                name: a1.current.state.value,
                                age: a2.current.state.value,
                                key: Date.now()
                            })
                            setStorage("goodsAttribute", JSON.stringify(originData))
                            setData([...originData])
                            // window.location.reload()
                            // console.log(a1.current.state.value, a2.current.state.value);
                        }}
                        onCancel={() => setVisible(false)}
                        width={700}
                        destroyOnClose={true}
                        okText="确定"
                        cancelText='取消'
                    >
                        <div>
                            <span>属性组名称：</span>
                            <Input ref={a1} />
                        </div>
                        <div>
                            <span>包含属性：</span>
                            <Input ref={a2} />
                        </div>

                    </Modal>
                </div>


                {/* 表格 */}
                <Form form={form} component={false}>
                    <Table
                        components={{
                            body: {
                                cell: EditableCell,
                            },
                        }}
                        bordered
                        dataSource={data}
                        columns={mergedColumns}
                        rowClassName="editable-row"
                        pagination={{
                            onChange: cancel,
                        }}
                    />
                </Form>

            </ClassifyStyle>
        </>
    );
}

export default Index;
